package cn.petplatform.petback.service.user.impl;

import cn.petplatform.dto.ResponseDto;
import cn.petplatform.petback.exceptions.DataTransformException;
import cn.petplatform.petback.mapper.RoleMapper;
import cn.petplatform.petback.mapper.UserMapper;
import cn.petplatform.petback.mapper.UserRoleMapper;
import cn.petplatform.petback.pojo.Role;
import cn.petplatform.petback.pojo.User;
import cn.petplatform.petback.pojo.UserRole;
import cn.petplatform.petback.pojo.expandenum.UserRoleType;
import cn.petplatform.petback.service.user.UserService;
import cn.petplatform.utils.JWTUtils;
import cn.petplatform.utils.MD5Util;
import cn.petplatform.utils.ProcessFileUtils;
import cn.petplatform.utils.UUIDUtils;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author LNL
 * @date 2021/5/13 15:52
 */
@Service("userLoginService")
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public ResponseDto login(String username, String password) {
        //用来存储user一些基本信息
        HashMap<String, Object> data = new HashMap<>();
        ResponseDto responseDto = null;
        //有一个bug，当用户名正确，密码不正确时，表示出现问题
        User user = userMapper.selectByUserName(username,UserRoleType.COMMON.toString());
        Optional<User> optionalUser = Optional.ofNullable(user);
        if (optionalUser.isPresent()) {//如果该用户不为空
            //密码正确时
            if(MD5Util.getMD5(password).equals(user.getPassword())) {
                //将name和id添加到token中的payload中去,并返回用户信息
                HashMap<String, String> map = new HashMap<>();
                map.put("name", user.getName());
                map.put("userId", user.getId());
                String token = JWTUtils.generateToken(map);
                data.put("token",token);
                //隐藏部分用户信息
                user.setPassword("");
                data.put("user",user);
                responseDto = new ResponseDto("1000", "登录成功", data);
            }else {
                responseDto = new ResponseDto("1001", "登录失败，密码错误");
            }
        } else {
            throw new DataTransformException("登录失败,用户名不存在");
        }
        return responseDto;
    }

    @Override
    public ResponseDto register(MultipartHttpServletRequest request) {
        ResponseDto responseDto = null;
        Map<String, String> fileData = ProcessFileUtils.processFile(request);
        if(!fileData.isEmpty()) {
            try {
                Map<String, String[]> userInfo = request.getParameterMap();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                User user = new User();
                user.setId(UUIDUtils.getUUID());
                user.setAddress(userInfo.get("address")[0]);
                user.setBirth(sdf.parse(userInfo.get("birth")[0]));
                user.setEmail(userInfo.get("email")[0]);
                user.setPhone(userInfo.get("phone")[0]);
                user.setSex(Integer.valueOf(userInfo.get("sex")[0]));
                user.setUsername(userInfo.get("username")[0]);
                user.setPassword(MD5Util.getMD5(userInfo.get("password")[0]));
                user.setName(userInfo.get("name")[0]);
                user.setPath(fileData.get("filePath"));
                user.setCreateTime(new Date());

                //创建role
                Role role = new Role();
                role.setId(UUIDUtils.getUUID());
                role.setRoleCode(UserRoleType.COMMON.toString());
                role.setCreateTime(new Date());
                role.setCreateUser(role.getId());
                role.setRoleName("普通用户");
                role.setRoleDesc("普通用户");
                role.setStatus(1);

                UserRole userRole = new UserRole();
                userRole.setId(UUIDUtils.getUUID());
                userRole.setRoleId(role.getId());
                userRole.setUserId(user.getId());

                int isInsertUser = userMapper.insertSelective(user);
                int isInsertRole = roleMapper.insertSelective(role);
                int isInsertUserRole = userRoleMapper.insertSelective(userRole);
                if(isInsertUser > 0 &&
                        isInsertRole > 0 &&
                        isInsertUserRole > 0) {
                    responseDto = new ResponseDto("1000","注册成功");
                }else {
                    ProcessFileUtils.failDeleteFile(fileData.get("filePath"));
                    responseDto = new ResponseDto("1001","注册失败");
                }
            } catch (Exception e) {
                ProcessFileUtils.failDeleteFile(fileData.get("filePath"));
                throw new RuntimeException("注册失败");
            }
        }
        return responseDto;
    }

    @Override
    public ResponseDto updateInfo(User user, HttpServletRequest request) {
        ResponseDto responseDto = null;
        //获取用户信息
        DecodedJWT userInfo = JWTUtils.getUserInfo(request.getHeader("token"));
        user.setEditUser(userInfo.getClaim("userId").asString());
        user.setEditTime(new Date());
        int isUpdate = userMapper.updateByPrimaryKeySelective(user);
        if (isUpdate > 0) {
            responseDto = new ResponseDto("1000","修改成功");
        }else{
            throw new RuntimeException("修改失败");
        }
        return responseDto;
    }

    @Override
    public ResponseDto deleteUser(String id, HttpServletRequest request) {
        ResponseDto responseDto = null;
        int isDelete = userMapper.deleteByPrimaryKey(id);
        if(isDelete > 0) {
            responseDto = new ResponseDto("1001","删除成功");
        }else {
            throw new RuntimeException("删除失败");
        }
        return responseDto;
    }

    @Override
    public ResponseDto getUserInfo(String id, HttpServletRequest request) {
        ResponseDto responseDto = null;
        User user = userMapper.selectByPrimaryKey(id);
        Optional<User> optionalUser = Optional.ofNullable(user);
        if(optionalUser.isPresent()) {
            user.setPassword("");
            responseDto = new ResponseDto("1000","个人信息",user);
        }else {
            responseDto = new ResponseDto("1001","获取信息失败");
        }
        return responseDto;
    }

    @Override
    public ResponseDto loginAdmin(String username, String password) {
        //用来存储user一些基本信息
        HashMap<String, Object> data = new HashMap<>();
        ResponseDto responseDto = null;
        //有一个bug，当用户名正确，密码不正确时，表示出现问题
        User user = userMapper.selectByUserName(username,UserRoleType.ADMIN.toString());
        Optional<User> optionalUser = Optional.ofNullable(user);
        if (optionalUser.isPresent()) {//如果该用户不为空
            //密码正确时
            if(MD5Util.getMD5(password).equals(user.getPassword())) {
                //将name和id添加到token中的payload中去,并返回用户信息
                HashMap<String, String> map = new HashMap<>();
                map.put("name", user.getName());
                map.put("userId", user.getId());
                String token = JWTUtils.generateToken(map);
                data.put("token",token);
                //隐藏部分用户信息
                user.setPassword("");
                data.put("user",user);
                responseDto = new ResponseDto("1000", "登录成功", data);
            }else {
                responseDto = new ResponseDto("1001", "登录失败");
            }
        } else {
            throw new DataTransformException("登录失败,用户名不存在或权限不足");
        }
        return responseDto;
    }
}
